package com.flot.yazb.widget.vitamioPlayer;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.flot.yazb.R;
import com.flot.yazb.base.BApplication;
import com.flot.yazb.video.Config;
import com.flot.yazb.model.user.UserModel;
import com.flot.yazb.home.moudle.EndZhiBoActivity;
import com.flot.yazb.widget.utils.GlideImageLoaderUtil;
import com.flot.yazb.widget.utils.NormalUtils;
import com.flot.yazb.widget.utils.ToastUtil;
import com.flot.yazb.widget.PayDialog;
import com.gc.materialdesign.views.ProgressWheel;
import com.gc.materialdesign.views.Slider;

import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.widget.VideoView;

public class VideoControllerView extends FrameLayout implements View.OnTouchListener, Slider.OnValueChangedListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnInfoListener, MediaPlayer.OnSeekCompleteListener {
    private static final long delayMillis = 1500;
    private VideoView mVideoView;
    private ProgressWheel mProgressWheel;
    private ImageButton viewPlay;
    private Slider slider;
    private Handler handler = new Handler();
    private Context context;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            slider.setVisibility(GONE);
        }
    };
    private View ivCover;
    private UserModel model = BApplication.getInstance().getUserModel();
    private String videoUrl;

    public VideoControllerView(Context context) {
        super(context);
        initView(context);
    }

    public VideoControllerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);

    }

    public VideoControllerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        this.context = context;
        View v = LayoutInflater.from(context).inflate(R.layout.view_video_controller, null);
        addView(v);
        mVideoView = findView(R.id.videoView);
        ivCover = findView(R.id.CoverView);
        mVideoView.setOnTouchListener(this);
        mVideoView.setOnPreparedListener(this);
        mVideoView.setOnBufferingUpdateListener(this);
        mVideoView.setOnCompletionListener(this);
        mVideoView.setOnErrorListener(this);
        mVideoView.setOnInfoListener(this);
        mVideoView.setOnSeekCompleteListener(this);
        //设置视频质量
//        mVideoView.setVideoQuality(VIDEOQUALITY_MEDIUM);
        //设置缓存大小，控制进入的速度
        mVideoView.setBufferSize(10);
//        mVideoView.setVideoLayout(VideoView.VIDEO_LAYOUT_SCALE,0);
//        mVideoView.getHolder().setFixedSize();
        mProgressWheel = findView(R.id.progressWheel);
        mProgressWheel.startSpinning();
        viewPlay = findView(R.id.button_play);
        slider = findView(R.id.slider);
        slider.setOnValueChangedListener(this);
        slider.setOnNumberIndicatorConvert(new Slider.OnNumberIndicatorConvert() {
            @Override
            public String covert(long val) {
                return MediaPlayerUtils.getVideoDisplayTime(val);
            }
        });
//        setVideoPlayButton();
    }

    private void setVideoPlayButton() {
        viewPlay.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_play_circle_selector));
        viewPlay.setVisibility(GONE);
        viewPlay.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                playStateChange();
            }
        });
    }

    @Deprecated
    private boolean isVideoPause() {
        return viewPlay.getVisibility() == View.VISIBLE;
    }

    private void updateTimeTask() {
        handler.removeCallbacks(runnable);
        handler.postDelayed(runnable, delayMillis);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
//        playStateChange();
        return false;
    }

    private void playStateChange() {
        updateTimeTask();
        if (!isVideoPause()) {
            slider.setVisibility(View.VISIBLE);
            slider.setValue(toInt(mVideoView.getCurrentPosition()));
            mProgressWheel.setVisibility(View.INVISIBLE);
            viewPlay.setVisibility(View.VISIBLE);
            mVideoView.pause();
        } else {
            viewPlay.setVisibility(View.INVISIBLE);
            mVideoView.start();
        }
    }


    private <T extends View> T findView(int id) {
        return (T) super.findViewById(id);
    }

    public void setVideoPath(String videoUrl) {
        mVideoView.setVideoPath(videoUrl);
        this.videoUrl = videoUrl;
    }

    /**
     * 开始播放
     */
    public void start() {
        mVideoView.start();
    }

    /**
     * 暂停播放
     */

    public void pause() {
        mVideoView.pause();
    }

    /**
     * 回复播放
     */
    public void resume(){
        mVideoView.resume();
    }


    /**
     * 释放资源
     */

    public void release() {
        mVideoView.stopPlayback();
    }


    public VideoView getVideoView() {
        return mVideoView;
    }


    public int toInt(long i) {
        return new Long(i).intValue();
    }

    public void setCoverView(String pic) {
        GlideImageLoaderUtil.loadImage((ImageView) ivCover, pic, R.mipmap.player_full_cover);
    }

    /**
     * 视频播放进度
     */
    private Handler progressHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mVideoView.getCurrentPosition() <= totalTime) {
                if ((mVideoView.getCurrentPosition() >= Config.DEFAULT_STOP_TIME )&&
                        (mVideoView.getCurrentPosition() <= (Config.DEFAULT_STOP_TIME + 1000))) {
                    if (model.getIsVip()==false) {
                        mVideoView.pause();
                        PayDialog dialog = new PayDialog(getContext(), "试看已结束，您还不是会员！");
                        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                if (closeListener!=null)
                                    closeListener.close();
                            }
                        });
                        dialog.show();
                    } else {

                    }
                    return;
                }
                sendEmptyMessageDelayed(0, 1000 - (mVideoView.getCurrentPosition() % 1000));
            }
        }
    };


    //监听播放器的 prepare 过程
    private long totalTime;

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        slider.setMin(0);
        slider.setMax(toInt(mediaPlayer.getDuration()));
        totalTime = mVideoView.getDuration();
        mediaPlayer.setPlaybackSpeed(1.0f);
        progressHandle.sendEmptyMessageDelayed(0, 1000);
    }

    @Override
    public void onValueChanged(int value) {
        updateTimeTask();
        mVideoView.seekTo(value);
        mVideoView.start();
        viewPlay.setVisibility(View.INVISIBLE);
        Log.d("new player", "onValueChanged: " + value);
    }


    //监听当前播放器已经缓冲的数据量占整个视频时长的百分比
    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
    }

    //监听播放结束的消息
    @Override
    public void onCompletion(MediaPlayer mp) {
//        viewPlay.setImageDrawable(context.getResources().getDrawable(R.mipmap.ic_replay_white_48dp, null));
//        viewPlay.setVisibility(VISIBLE);
//        viewPlay.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mVideoView.seekTo(0);
//                setVideoPlayButton();
//            }
//        });

        Log.d("new player", "onCompletion: ");
        if (closeListener != null)
            closeListener.endZhibo();
        //判断网络是否联通
        if (!NormalUtils.isNetworkConnected(getContext())) {
            ToastUtil.showToast(getContext(), "网络不通，请查看您的网络情况");
        }
    }


    //用于监听播放器的错误消息
    //如果处理了错误返回true，否则返回false。返回false或没有设置OnErrorListener将引发OnCompletionListener被调用。
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        Log.d("new player", "onError: " + what + "    " + extra);
        // 视频源没有数据notfound  875574520
        // 当生未知错误 Error (1, -5)
        // 4xxx  1482175736
//        if (what == 1 && (extra == -875574520 || extra == -5 || extra==-1482175736)) {
//
//        }

        if (what==1 && extra==-110){
            //释放资源
            release();
            mVideoView.setVideoPath(videoUrl);
            return true;
        }
        release();
        if (closeListener != null)
            closeListener.endZhibo();
        return true;
    }

    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        Log.d("new player", "onInfo: " + what + "    " + extra);
        switch (what) {
            case MediaPlayer.MEDIA_INFO_BUFFERING_END://结束缓冲
                mProgressWheel.setVisibility(View.INVISIBLE);
                ivCover.setVisibility(GONE);
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_START://MediaPlayer暂停播放等待缓冲更多数据。
                mProgressWheel.setVisibility(View.VISIBLE);
                ivCover.setVisibility(VISIBLE);
                mVideoView.start();
                break;
            case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING://视频过于复杂，无法解码：不能快速解码帧。此时可能只能正常播放音频 700
//                release();
//                mVideoView.setVideoPath(videoUrl);
                break;
        }
        return true;
    }

    @Override
    public void onSeekComplete(MediaPlayer mp) {
        Log.d("new player", "onSeekComplete: ");
    }

    private CloseListener closeListener;


    public void endZhibo() {
        getContext().startActivity(new Intent(getContext(), EndZhiBoActivity.class));
    }

//    public void setVideoSize(int screenWidth, int screenHeight) {
//        mVideoView.setVideoLayout(VideoView.VIDEO_LAYOUT_SCALE,0);
//        mVideoView.getHolder().setFixedSize(screenWidth,screenHeight);
//        mVideoView.setPlayerHeight(screenWidth,screenHeight);
//    }

    public interface CloseListener {
        void close();

        void endZhibo();
    }

    public void setONcLoseListener(CloseListener listener) {
        closeListener = listener;
    }
}
